package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private ITravelCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public TravelComment saveOrUpdate(TravelComment comment) {
        if(!StringUtils.hasLength(comment.getId())){
            comment.setCreateTime(new Date());
        }
        //引用评论
        if(StringUtils.hasLength(comment.getRefComment().getId())){
            TravelComment refComment = repository.findById(comment.getRefComment().getId()).get();
            comment.setRefComment(refComment);
        }



        repository.save(comment);
        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {
        //查询条件
        Query query = new Query();

        //判断
        if(qo.getTravelId() != -1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        //count 查询总数
        long count = template.count(query, TravelComment.class);

        //判断是否有符合条件的评论
        if(count == 0){
            return Page.empty();
        }
        //分页条件
        Pageable pageable = PageRequest.of(qo.getCurrentPage() -1 ,qo.getPageSize(),new Sort(Sort.Direction.DESC,"createTime"));
        query.with(pageable);


        List<TravelComment> travelComments = template.find(query, TravelComment.class);

        return new PageImpl(travelComments,pageable,count);
    }


}
